package com.community.interceptor;

import com.community.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        
        // 放行登录、注册、静态资源等
        if (requestURI.contains("/loginForm") ||
            requestURI.contains("/login") ||
            requestURI.contains("/sign-up-form") ||
            requestURI.contains("/add-user") ||
            requestURI.contains("/css/") ||
            requestURI.contains("/images/")) {
            return true;
        }
        
        HttpSession session = request.getSession(false);
        // 检查 session 里是否有 user
        if (session != null && session.getAttribute("user") != null) {
            return true;
        } else {
            // 未登录访问受保护资源时添加提示信息
            session = request.getSession();
            session.setAttribute("message", "请先登录系统！");
            response.sendRedirect(request.getContextPath() + "/loginForm");
            return false;
        }
    }
}